package com.xizi.producer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.*;

import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @author xizizzz
 * @description: 同步发送 .get() 方法
 * @date 2021-7-3上午 09:54
 */
public class SyncProducer {
    public static void main(String[] args) throws Exception {
        //1. 创建Kafka生产者的配置信息
        Properties props = new Properties();
        //2. 指定连接的Kafka集群  broker-list
        props.put("bootstrap.servers", "zookeeper1:9092");
        //3. ack应答级别
        props.put("acks", "all");
        //4. 重试次数
        props.put("retries", 1);
        //5. 批次大小
        props.put("batch.size", 16384);
        //6. 等待时间
        props.put("linger.ms", 1);
        //7. RecordAccumulator 缓冲区大小
        props.put("buffer.memory", 33554432);
        //8. key value序列化类
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        //9. 创建生产者对象
        Producer<String, String> producer = new KafkaProducer<>(props);
        //10. 发送数据
        for (int i = 0; i < 10; i++) {
            // 调用get方法 变成同步了
            RecordMetadata first = producer.send(new ProducerRecord<String, String>("first", "xizi--" + i), new Callback() {
                //回调函数， 该方法会在 Producer 收到 ack 时调用，为异步调用
                @Override
                public void onCompletion(RecordMetadata metadata, Exception exception) {
                    if (exception == null) {
                        System.out.println(metadata.partition() + " - " + metadata.offset());
                    } else {
                        exception.printStackTrace();
                    }
                }
            }).get();
        }
        //11. 关闭资源
        producer.close();
    }
}
